package com.xl.config;

import com.xl.constants.QueueConstants;
import com.xl.intercepter.WebsocketIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 配置websocket的endpoint（用于链接websocket ，应用前缀（用于指定controller方法），
 * 和代理前缀（消息消息队列 /前缀/目的地）
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final String[] APPLICATION_PREFIX = {"/nmsMessage", "/nmsQueue"};

    private WebsocketIntercepter websocketIntercepter;

    public WebsocketConfig(WebsocketIntercepter websocketIntercepter) {
        this.websocketIntercepter = websocketIntercepter;
    }

    //注册endpoint ， 用于连接websocket
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/myws","/otherws") //可以有多个endpoint，连接之后都可以向队列发送消息
                .addInterceptors(websocketIntercepter)
                //注意这里别写错了，setAllowedOrigins，不是setAllowedOriginsPatterns()
                .setAllowedOrigins("*")
        ;
    }


    /**
     * 用于注册应用前缀和代理前缀，
     *
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //注册代理前缀，用于项队列里面发送消息
        registry.enableSimpleBroker(
                QueueConstants.GROUP_ALARM_QUEUE,
                QueueConstants.HOME_ALARM_QUEUE,
                QueueConstants.LINK_ALARM_QUEUE,
                QueueConstants.MODEL_ALARM_QUEUE,
                QueueConstants.RECENTLY_ALARM_QUEUE
        );
        //注册应用前缀，带有应用前缀的请求，将进入到控制器中
        registry.setApplicationDestinationPrefixes(APPLICATION_PREFIX);
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(websocketIntercepter);
    }
}
